const injectList = [jp, qe, Pp]


window._jp = jp;
window._qe = qe;

window._jp = Pp;
window._qe = qe;

function generateUUID() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}
// 日志上报
function REPORT_MSG(op, data = {}, rid = "", status = "done") {
  return fetch("/__wx_channels_api/report", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      op,
      data,
      rid,
      status,
    }),
  });
}

async function get_list(_query) {
  async function searchData(query) {
    const _u = {
      query: query,
      scene: 19,
      requestId: Date.now().toString(),
    };
    return window._jp.finderSearch(_u); // 返回 Promise
  }
  const _query_data = await searchData(_query);
  return _query_data;
}
async function get_user_detail(_username, _title) {
  const _list = [];
  let _lastBuffer = "";
  let previousBuffer = null;
  let retryCount = 0;
  const maxRetries = 50; // 5000 个视频上限
  REPORT_MSG("开始轮询查询标题:", _title);
  try {
    while (retryCount < maxRetries) {
      await new Promise((resolve) => setTimeout(resolve, 100));
      const query = await user_detail(_username, _lastBuffer);
      if (query.data && query.data.lastBuffer) {
        for (let i = 0; i < query.data.object.length; i++) {
          if (query.data.object[i].objectDesc.description.trim() == _title) {
            REPORT_MSG("找到目标: ", _title);
            // return query.data.object[i];
          }
          REPORT_MSG(query.data.object[i].objectDesc.description.trim());
        }

        _list.push(query.data.object);
        if (query.data.lastBuffer === previousBuffer) {
          REPORT_MSG("检测到相同_lastBuffer，终止轮询");
          break;
        }
        previousBuffer = query.data.lastBuffer;
        _lastBuffer = query.data.lastBuffer;
        retryCount++;
        REPORT_MSG(`检测到新_lastBuffer，开始第 ${retryCount} 次轮询...`);
      } else {
        REPORT_MSG("没有更多数据了");
        break;
      }
    }
    return _list;
  } catch (error) {
    REPORT_MSG("获取用户详情失败:", error);
  }
  async function user_detail(username, buffer) {
    const _n = {
      username: username,
      objectId: "0",
      finderUsername:
        "v2_060000231003b20faec8c6e18f18c2d4cb0deb36b077b869d50c480eda28b31d4ac0f7c43bb8@finder",
      lastBuffer: buffer,
      needFansCount: 0,
    };
    return window._qe.finderUserPage(_n);
  }
}

//virtual 搜索const Bp = new Hf
// 赋值
function get_run(_name, _title) {
  return get_list(_name)
    .then((res) => {
      const respJson = res.data;
      if (!_title) {
        return respJson;
      }
      for (let i = 0; i < respJson.infoList.length; i++) {
        const nickname = respJson.infoList[i].contact.nickname;
        if (_name == nickname) {
          const _username = respJson.infoList[i].contact.username;
          REPORT_MSG("找到目标", _name);
          return get_user_detail(_username, _title).then((result) => {
            return result;
          });
        } else {
          REPORT_MSG("未找到目标", _name);
        }
        return []; // 如果没有找到目标，返回空数组
      }
    })
    .catch((error) => {
      REPORT_MSG("流程异常:", error);
      throw error;
    });
}

window.document.addEventListener("DOMContentLoaded", function () {
// // 调试阶段打开，用于版本更新的时候使用，打开后会导致 main.go 的 http 对应 ws timeout
// // 拦截 web 和 客户端的 hook
//   REPORT_MSG("web hook invoke", Object.keys(window.WeixinJSBridge));
//   const invoke = window.WeixinJSBridge.invoke;
//   REPORT_MSG("hook keys type ", Object.prototype.toString.call(invoke));
//   window.WeixinJSBridge.invoke = (...args) => {
//     // 任意参数中有 url 则调用打印
//     const existUrl = args.some((arg) => {
//       if (typeof arg === "object") {
//         for (const key in arg) {
//           if (key === "url") {
//             return arg[key].indexOf('report') === -1;
//           }
//         }
//       }
//       return false;
//     });
//     existUrl && REPORT_MSG("invoke args", args);
//     if (args[0] === "finderH5ExtTransfer" && typeof args[1] === "object") {
//       existUrl && REPORT_MSG("invoke req", args[1]);
//     }
//     existUrl && REPORT_MSG("typeof callback ", Object.prototype.toString.call(args[2]));
//     if (Object.prototype.toString.call(args[2]) === "[object AsyncFunction]") {
//       existUrl && REPORT_MSG("callback", args[2]);
//       const originCallback = args[2];
//       args[2] = (res) => {
//         existUrl && REPORT_MSG("invoke res", res);
//         originCallback(res);
//       };
//     }
//     invoke.apply(window.WeixinJSBridge, args);
//   };

  // 搜索 api 挂载
  try {
    // 测试是否更新版本了
    if (typeof window._jp === "undefined" || typeof window._qe === "undefined") {
      REPORT_MSG("请更新版本");
    }

    if (typeof window._jp.finderSearch === "undefined") {
      REPORT_MSG("版本升级了，请及时更新版本", Object.keys(window._jp).join(""));
    }

    // 开启定时任务
    setInterval(() => {
      REPORT_MSG("START_REQUEST")
        .then((res) => {
          res
            .json()
            .then((json) => {
              // 搜索
              if (json.op === "/search") {
                const id = json.rid;

                const { name, title } = json.data;
                REPORT_MSG("inject 正在抓取数据", json);
                get_run(name, title)
                  .then((data) => {
                    REPORT_MSG(`SEND_RESPONSE`, data, id);
                  })
                  .catch((e) => {
                    REPORT_MSG("SEND_RESPONSE", e.message, id);
                  });
              }
            })
            .catch((e) => {
              REPORT_MSG("SEND_RESPONSE", e.message, id);
            });
        })
        .catch((e) => {
          REPORT_MSG("请求异常:", e.message);
        });
    }, 100);
  } catch (e) {
    REPORT_MSG("注入异常:", e.message);
  }
});